from asciimatics.exceptions import NextScene, StopApplication
from asciimatics.screen import ManagedScreen
from asciimatics.scene import Scene
from asciimatics.widgets import *
from sqliteController import Client

OLDFIELD = [("", "", "", "", "", "")]
N = 0

class ViewView(Frame):
    def __init__(self, screen, client):
        super(ViewView, self).__init__(screen,
                                       screen.height ,
                                       screen.width ,
                                       hover_focus=True,
                                       on_load=self._reload,
                                       title="BooksManagementSystem")
        self._client = client
        layout = Layout([100], fill_frame=True)
        self.add_layout(layout)
        self.tu = OLDFIELD[0]
        self.l2 = Text("Name:" )
        self.l3 = Text("Price:")
        self.l4 = Text("Author:")
        self.l5 = Text("Date of publication:")
        self.l6 = TextBox(5, "Notes:", "notes", as_string=True)
        self.l2.value = self.tu[1]
        self.l3.value = str(self.tu[2])
        self.l4.value = self.tu[3]
        self.l5.value = self.tu[4]
        self.l6.value = self.tu[5]
        layout.add_widget(self.l2)
        layout.add_widget(self.l3)
        layout.add_widget(self.l4)
        layout.add_widget(self.l5)
        layout.add_widget(self.l6)
        layout2 = Layout([1, 1])
        self.add_layout(layout2)
        layout2.add_widget(Button("Edit", self._edit), 0)
        layout2.add_widget(Button("Cancel", self._cancel), 1)
        self.fix()
    
    def _reload(self):
        self.tu = OLDFIELD[0]
        self.l2.value = self.tu[1]
        self.l3.value = str(self.tu[2])
        self.l4.value = self.tu[3]
        self.l5.value = self.tu[4]
        self.l6.value = self.tu[5]

    def _edit(self):
        try:
            if self.l2.value and self.l3.value and self.l4.value:
                self._client.update({"NAME":f"'{self.tu[1]}'"}, {"NAME":f"'{self.l2.value}'"})
                self._client.update({"PRICE":f"{self.tu[2]}"}, {"PRICE":f"{self.l3.value}"})
                self._client.update({"AUTHOR":f"'{self.tu[3]}'"}, {"AUTHOR":f"'{self.l4.value}'"})
            self._client.update({"DATE":f"'{self.tu[4]}'"}, {"DATE":f"'{self.l5.value}'"})
            self._client.update({"NOTE":f"'{self.tu[5]}'"}, {"NOTE":f"'{self.l6.value}'"})
        except:
            raise NextScene("Main")
        else:
            raise NextScene("Main")

    def _cancel(self):
        raise NextScene("Main")

class FormView(Frame):

    def __init__(self, screen, client, msg):
        super(FormView, self).__init__(screen,
                                       screen.height ,
                                       screen.width ,
                                       hover_focus=True,
                                       title="BooksManagementSystem")
        self._client = client
        self.msg = msg
        layout = Layout([100], fill_frame=True)
        self.add_layout(layout)
        self.name_input = Text("Name(*):")
        self.price_input = Text("Price(*):")
        self.author_input = Text("Author(*):")
        self.date_input = Text("Date of publication:")
        self.note_input  = TextBox(5, "Notes:", "notes", as_string=True)
        layout.add_widget(self.name_input)
        layout.add_widget(self.price_input)
        layout.add_widget(self.author_input)
        layout.add_widget(self.date_input)
        layout.add_widget(self.note_input)
        layout2 = Layout([1, 1])
        self.add_layout(layout2)
        layout2.add_widget(Button("Ok", self._ok), 0)
        layout2.add_widget(Button("Cancel", self._cancel), 1)
        self.fix()
    
    def reset(self):
        self.name_input.value = ""
        self.price_input.value = ""
        self.author_input.value = ""
        self.date_input.value = ""
        self.note_input.value = ""

    def _ok(self):
        s1 = self.name_input.value
        s2 = self.price_input.value
        s3 = self.author_input.value
        s4 = self.date_input.value
        s5 = self.note_input.value
        if s1 and s2 and s3:
            try:
                self._client.insert({"ID":f"{N}", "NAME":f"'{s1}'", "PRICE":f"{s2}", "AUTHOR":f"'{s3}'", 
                    "DATE":f"'{s4}'", "NOTE":f"'{s5}'"})
            except:
                raise NextScene("Main")
            else:
                raise NextScene("Main")
            
        else:
            raise NextScene("Main")

    def _cancel(self):
        raise NextScene("Main")

class MainView(Frame):
    def __init__(self, screen, client):
        super(MainView, self).__init__(screen,
                                       screen.height ,
                                       screen.width ,
                                       hover_focus=True,
                                       on_load=self._reload_list_view,
                                       title="BooksManagementSystem")
        self._client = client
        layout = Layout([100], fill_frame=True)
        self.add_layout(layout)
        self._list_view = ListBox(
            Widget.FILL_FRAME, 
            list(self._client.select("NAME", "NAME")), 
            on_select=self._on_pick, 
            name="fruits")
        layout.add_widget(self._list_view)
        layout2 = Layout([1, 1, 1])
        self.add_layout(layout2)
        layout2.add_widget(Button("Add", self._add), 0)
        layout2.add_widget(Button("Delete", self._delete), 1)
        layout2.add_widget(Button("Quit", self._quit), 2)
        self.fix()

    def _reload_list_view(self):
        global N
        self._list_view.options = list(self._client.select("NAME", "NAME"))
        N = len(self._list_view.options)

    def _on_pick(self):
        if self._list_view.value:
            global OLDFIELD
            OLDFIELD = list(self._client.find("ID,NAME,PRICE,AUTHOR,DATE,NOTE", {"NAME":f"'{self._list_view.value}'"}))
            raise NextScene("View")

    def _delete(self):
        self.save()
        self._client.delete({"NAME":f"'{self._list_view.value}'"})
        self._reload_list_view()

    def _add(self):
        raise NextScene("Add")
    
    @staticmethod
    def _quit():
        raise StopApplication("User pressed quit")

def demo():
    with ManagedScreen() as screen:
        client = Client("books")
        try:
            sqlLs = [client._cf("ID", "INT", 1, 1), client._cf("NAME", "TEXT", 0, 1), client._cf("PRICE", "DOUBLE", 0, 1),
                client._cf("AUTHOR", "TEXT", 0, 1), client._cf("DATE", "TEXT", 0, 0), client._cf("NOTE", "TEXT", 0, 0)]
            client.create(",".join(sqlLs))
        except:
            pass
        scenes = [
            Scene([MainView(screen, client)], -1, name="Main"),
            Scene([FormView(screen, client, "add")], -1, name="Add"),
            Scene([ViewView(screen, client)], -1, name="View"),
        ]
        screen.play(scenes)


demo()
